package user.Controller.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;

@WebFilter(urlPatterns = "/*")
public class Filter implements javax.servlet.Filter {
    //初始化：web服务器启动，就以及初始化了，随时等待过滤对象出现！
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化");
    }

    //Chain : 链
          /*
          1. 过滤中的所有代码，在过滤特定请求的时候都会执行
          2. 必须要让过滤器继续同行
              chain.doFilter(request,response);
           */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ArrayList allowPathList = new ArrayList();
        allowPathList.add("/verifiCode");
        allowPathList.add("/imgCode");
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        String currentUrl = httpRequest.getServletPath();
        if(!allowPathList.contains(currentUrl)){
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=UTF-8");  //除去这两个servlet外其他接口全部执行该过滤器
        }
        System.out.println("CharacterEncodingFilter执行前....");
        chain.doFilter(request,response);
         //让我们的请求继续走，如果不写，程序到这里就被拦截停止！
        System.out.println("CharacterEncodingFilter执行后....");
    }

    //销毁：web服务器关闭的时候，过滤器会销毁
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁");
    }
}

